﻿using System.Collections;
using System.Collections.Generic;
using System.Net.Sockets;
using UnityEngine;

namespace KFGame
{
    public class KFSockServer
    {
        KFSocketPoll poll;

        public delegate void ReceiveMessage(string ip, string msg);

        public ReceiveMessage OnMessage;

        public KFSockServer()
        {
        }

        public void init()
        {
            string group = "KFINFO";
            string iniPath =
                Application.streamingAssetsPath + "/KFConfig/gameservers.ini";
            INIParser iNIParser = new INIParser();
            iNIParser.Open(iniPath);

            KFSocketPoll.port = iNIParser.ReadValue(group, "Port", 8888);
            KFSocketPoll.IpStr = iNIParser.ReadValue(group, "ListenIP", "0.0.0.0");
            KFSocketPoll.linknumber = iNIParser.ReadValue(group, "MaxLink", 20);
            iNIParser.Close();

            poll = new KFSocketPoll();
            poll.GetReceive += onReceive;

            poll.Start();
        }

        //接收客户收息
        void onReceive(Socket socket, ByteBuffer buff)
        {
            if (OnMessage != null)
                OnMessage(socket.RemoteEndPoint.ToString(), buff.ReadString());
        }

        //关服务
        public void Close()
        {
            if (poll == null) return;
            poll.GetReceive -= onReceive;
            poll.Close();
        }

        //发送信息给指定客户
        public void SendMessage(string ip, string msg)
        {
            KFSocketPoll.SendMessage(poll.GetCilent(ip), msg);
        }

        //发送所有信息给客户端
        public void SendMessage(string msg)
        {
            if (poll == null) return;
            poll.SendAllMessage(msg);
        }
    }

}